#!/usr/bin/python
from Tkinter import *
from time import sleep
from gui import configuration
import tkMessageBox
from thread import start_new_thread

__all__ = ['MasterWindow']

class MasterWindow:
    def __init__(self, state, app):
        self.state = state
        self.app = app
        
        masterWindow = Tk()
        masterWindow.configure(padx=20, pady=20)
        masterWindow.title("Daily Digest")

        # for py2app - hides the tcl window
        if (sys.platform != "win32") and hasattr(sys, 'frozen'):
            masterWindow.tk.call('console', 'hide')

        frame = Frame(masterWindow).pack
        self.lbl = Label(masterWindow, height=3)
        self.lbl.grid(row=0, columnspan=3)    
  
        self.chkVal = IntVar()
        chk = Checkbutton(masterWindow, text="Send digest on load?", variable=self.chkVal)
        chk.bind("<Button-1>", self.toggle_send)
        chk.grid(row=1, columnspan=3)       
        
        if self.state.settings['send_on_load'] == True: 
            chk.select()
            self.start_send(state, app)
        else:
            self.lbl.configure(text="Daily Digest")

        watcher = start_new_thread(self.watch_for_messages, ())
        errorChecker = start_new_thread(self.catch_errormessage, ())
        
        def g(): self.start_send(state, app)
        def f(): self.feedListScreen = configuration.FeedListScreen(masterWindow, self.state, self.app) 
        def y(): self.configurationScreen = configuration.ConfigurationScreen(masterWindow, self.state, self.app)

        btnG = Button(masterWindow, text="Send Now", command=g).grid(row=3, column=0)
        btnF = Button(masterWindow, text="Feeds", command=f).grid(row=3, column=1)
        btnC = Button(masterWindow, text="Setup", command=y).grid(row=3, column=2)

        masterWindow.mainloop()

    def start_send(self, state, app):
        self.lbl.configure(text="Daily Digest: Working...")
        sendThread = start_new_thread(app.send_digest, (state, ))

    
    def watch_for_messages(self):
        while True:
            if self.app.message <> "":
                self.lbl.configure(text="Daily Digest: %s" % self.app.message)
                self.app.message = ""
                sleep(1)

    def catch_errormessage(self):
        while True:
            if self.app.errorMessage <> "":
                tkMessageBox.showerror("Oops...",self.app.errorMessage)
                self.app.errorMessage = ""
                self.lbl.configure(text="Daily Digest")
                sleep(1)

    def toggle_send(self, e):
        if self.chkVal.get() == 1: 
            self.state.settings['send_on_load'] = False
        else:
            self.state.settings['send_on_load'] = True
        self.state.save_settings()
